<template>
  <div class="task-manager">
    <!-- 左侧编辑边栏 -->
    <v-navigation-drawer
      v-model="editDrawer"
      temporary
      location="left"
      width="400"
    >
      <v-card flat>
        <v-card-title class="d-flex align-center justify-space-between">
          <span>编辑任务</span>
          <v-btn
            icon="mdi-close"
            variant="text"
            size="small"
            @click="closeEditDrawer"
          />
        </v-card-title>
        <v-divider />
        <v-card-text>
          <v-form v-if="currentEditingTask">
            <!-- 任务标题 -->
            <v-text-field
              v-model="currentEditingTask.title"
              label="任务标题"
              variant="outlined"
              density="compact"
              class="mb-4"
            />
            
            <!-- 任务描述 -->
            <v-textarea
              v-model="currentEditingTask.description"
              label="任务描述"
              variant="outlined"
              density="compact"
              rows="3"
              class="mb-4"
            />
            
            <!-- 任务分类 -->
            <v-select
              v-model="currentEditingTask.category"
              :items="['工作', '学习', '生活', '其他']"
              label="任务分类"
              variant="outlined"
              density="compact"
              class="mb-4"
            />
            
            <!-- 截止时间 -->
             <v-text-field
               :model-value="currentEditingTask.deadline ? new Date(currentEditingTask.deadline).toLocaleString('zh-CN') : ''"
               label="截止时间"
               variant="outlined"
               density="compact"
               readonly
               append-inner-icon="mdi-calendar"
               @click:append-inner="openDeadlineDialogForEdit"
               class="mb-4"
             />
             
             <!-- 提醒时间 -->
             <v-text-field
               :model-value="currentEditingTask.reminder ? new Date(currentEditingTask.reminder).toLocaleString('zh-CN') : ''"
               label="提醒时间"
               variant="outlined"
               density="compact"
               readonly
               append-inner-icon="mdi-bell"
               @click:append-inner="openReminderDialogForEdit"
               class="mb-4"
             />
             
             <!-- 重复设置 -->
             <v-text-field
               :model-value="getRepeatText(currentEditingTask.repeat)"
               label="重复设置"
               variant="outlined"
               density="compact"
               readonly
               append-inner-icon="mdi-repeat"
               @click:append-inner="openRepeatDialogForEdit"
               class="mb-4"
             />
            
            <!-- 操作按钮 -->
            <div class="d-flex gap-2 mt-6">
              <v-btn
                color="primary"
                variant="flat"
                @click="saveEditedTask"
                block
              >
                保存修改
              </v-btn>
              <v-btn
                color="grey"
                variant="outlined"
                @click="closeEditDrawer"
                block
              >
                取消
              </v-btn>
            </div>
          </v-form>
        </v-card-text>
      </v-card>
    </v-navigation-drawer>




    <!-- 添加新任务 -->
    <v-card class="mx-auto mt-4"  elevation="1" style="position: sticky; top: 0; z-index: 10;"> 
      <v-card-text>
        <v-text-field

          v-model="newTaskTitle"
          label="添加新任务"
          variant="underlined"
          density="compact"
          @keyup.enter="addTask"
        >
          <template v-slot:prepend-inner>
            <v-btn
              icon="mdi-plus"
              size="small"
              variant="text"
              color="primary"
              @click="addTask"
              :disabled="!newTaskTitle.trim()"
            />
          </template>
            <template v-slot:append>
              <div class="d-flex gap-1 align-center">
                <v-icon
                  icon="mdi-clock-outline"
                  size="small"
                  variant="text"
                  color="primary"
                  @click="openReminderDialog"
                  :disabled="!newTaskTitle.trim()"
                />
                <v-icon
                  icon="mdi-calendar"
                  size="small"
                  variant="text"
                  color="primary"
                  @click="openDeadlineDialog"
                  :disabled="!newTaskTitle.trim()"
                />
                <v-icon
                  icon="mdi-repeat"
                  size="small"
                  variant="text"
                  color="primary"
                  @click="openRepeatDialog"
                  :disabled="!newTaskTitle.trim()"
                />
              </div>
            </template>
        </v-text-field>
      </v-card-text>
    </v-card>
    <!-- 任务列表 -->
    <v-card
      v-for="task in tasks"
      :key="task.id"
      class="mb-4 mx-auto"
      elevation="2"
      style="cursor: pointer;"
      @click="openEditDrawer(task)"
    >
      <v-card-text class="d-flex align-center">
        <!-- 完成状态复选框 -->
        <v-checkbox
          v-model="task.completed"
          color="primary"
          class="mr-3"
          @change="toggleTask(task)"
          @click.stop
        />
        
        <!-- 任务内容 -->
        <div class="flex-grow-1">
          <div 
            :class="{
              'text-decoration-line-through text-grey': task.completed,
              'text-body-1': !task.completed
            }"
          >
            {{ task.title }}
          </div>
          <div class="text-caption text-grey" v-if="task.description">
            {{ task.description }}
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <v-btn
          icon="mdi-delete"
          size="small"
          variant="text"
          color="error"
          @click.stop="deleteTask(task.id)"
        />
      </v-card-text>
    </v-card>
    
    
    <!-- 截止时间对话框 -->
    <v-dialog v-model="deadlineDialog" max-width="400px">
      <v-card>
        <v-card-title>设置截止时间</v-card-title>
        <v-card-text>
          <v-date-picker
            v-model="selectedDeadline"
            color="primary"
            show-adjacent-months
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="deadlineDialog = false">取消</v-btn>
          <v-btn color="primary" @click="setDeadline">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 提醒时间对话框 -->
    <v-dialog v-model="reminderDialog" max-width="400px">
      <v-card>
        <v-card-title>设置提醒时间</v-card-title>
        <v-card-text>
          <v-date-picker
            v-model="selectedReminderDate"
            color="primary"
            show-adjacent-months
            class="mb-4"
          />
          <v-time-picker
            v-model="selectedReminderTime"
            color="primary"
            format="24hr"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="reminderDialog = false">取消</v-btn>
          <v-btn color="primary" @click="setReminder">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 重复设置对话框 -->
    <v-dialog v-model="repeatDialog" max-width="400px">
      <v-card>
        <v-card-title>设置重复</v-card-title>
        <v-card-text>
          <v-select
            v-model="selectedRepeat"
            :items="repeatOptions"
            label="重复频率"
            variant="outlined"
          />
          <v-text-field
            v-if="selectedRepeat === 'custom'"
            v-model="customRepeatDays"
            label="自定义天数"
            type="number"
            variant="outlined"
            class="mt-3"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="repeatDialog = false">取消</v-btn>
          <v-btn color="primary" @click="setRepeat">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useTaskStore } from '@/stores/taskStore'

// 使用Pinia store
const taskStore = useTaskStore()
const { tasks, addTask: storeAddTask, toggleTask: storeToggleTask, deleteTask: storeDeleteTask, updateTask: storeUpdateTask } = taskStore

// 计算属性
const allTasks = computed(() => taskStore.tasks)
const pendingTasks = computed(() => allTasks.value.filter(task => !task.completed))
const completedTasks = computed(() => allTasks.value.filter(task => task.completed))
const importantTasks = computed(() => allTasks.value.filter(task => task.isImportant))
const todayTasks = computed(() => {
  const today = new Date()
  return allTasks.value.filter(task => {
    if (!task.deadline) return false
    const dueDate = new Date(task.deadline)
    return dueDate.toDateString() === today.toDateString()
  })
})

// 检查任务是否过期
const isOverdue = (task) => {
  if (!task.deadline || task.completed) return false
  const now = new Date()
  const deadline = new Date(task.deadline)
  return deadline < now
}

// 全局任务统计
const globalStats = computed(() => {
  const total = allTasks.value.length
  const completed = completedTasks.value.length
  const pending = pendingTasks.value.length
  const important = importantTasks.value.length
  const today = todayTasks.value.length
  const overdue = pendingTasks.value.filter(task => isOverdue(task)).length
  const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0
  
  return {
    total,
    completed,
    pending,
    important,
    today,
    overdue,
    completionRate
  }
})

// 新任务输入
const newTaskTitle = ref('')

// 对话框状态
const deadlineDialog = ref(false)
const reminderDialog = ref(false)
const repeatDialog = ref(false)

// 编辑边栏状态
const editDrawer = ref(false)
const currentEditingTask = ref(null)

// 临时存储的设置值
const selectedDeadline = ref(null)
const selectedReminderDate = ref(null)
const selectedReminderTime = ref(null)
const selectedRepeat = ref(null)
const customRepeatDays = ref(1)

// 重复选项
const repeatOptions = [
  { title: '不重复', value: null },
  { title: '每天', value: 'daily' },
  { title: '每周', value: 'weekly' },
  { title: '每月', value: 'monthly' },
  { title: '每年', value: 'yearly' },
  { title: '自定义', value: 'custom' }
]

// 当前任务的临时设置
const currentTaskSettings = reactive({
  deadline: null,
  reminder: null,
  repeat: null
})

// 添加任务
const addTask = () => {
  if (newTaskTitle.value.trim()) {
    const newTask = {
      title: newTaskTitle.value.trim(),
      completed: false,
      category: 'tasks', // 默认分类
      deadline: currentTaskSettings.deadline,
      reminder: currentTaskSettings.reminder,
      repeat: currentTaskSettings.repeat ? {
        type: currentTaskSettings.repeat.startsWith('custom_') ? 'custom' : currentTaskSettings.repeat,
        customDays: currentTaskSettings.repeat.startsWith('custom_') ? parseInt(currentTaskSettings.repeat.split('_')[1]) : undefined
      } : undefined
    }
    storeAddTask(newTask)
    newTaskTitle.value = ''
    // 重置临时设置
    currentTaskSettings.deadline = null
    currentTaskSettings.reminder = null
    currentTaskSettings.repeat = null
  }
}

// 打开截止时间对话框
const openDeadlineDialog = () => {
  selectedDeadline.value = currentTaskSettings.deadline
  deadlineDialog.value = true
}

// 设置截止时间
const setDeadline = () => {
  if (selectedDeadline.value) {
    if (currentEditingTask.value) {
      // 编辑模式：直接更新当前编辑任务
      currentEditingTask.value.deadline = selectedDeadline.value.toISOString()
    } else {
      // 新建模式：更新临时设置
      currentTaskSettings.deadline = selectedDeadline.value
    }
    deadlineDialog.value = false
  }
}

// 打开提醒对话框
const openReminderDialog = () => {
  if (currentTaskSettings.reminder) {
    const reminderDate = new Date(currentTaskSettings.reminder)
    // 检查日期是否有效
    if (!isNaN(reminderDate.getTime())) {
      selectedReminderDate.value = reminderDate.toISOString().split('T')[0]
      selectedReminderTime.value = reminderDate.toTimeString().split(' ')[0].slice(0, 5)
    } else {
      console.error('Invalid reminder date:', currentTaskSettings.reminder)
      selectedReminderDate.value = null
      selectedReminderTime.value = null
    }
  } else {
    selectedReminderDate.value = null
    selectedReminderTime.value = null
  }
  reminderDialog.value = true
}

// 设置提醒
const setReminder = () => {
  if (selectedReminderDate.value && selectedReminderTime.value) {
    const reminderDateTime = new Date(`${selectedReminderDate.value}T${selectedReminderTime.value}`)
    // 检查日期是否有效
    if (!isNaN(reminderDateTime.getTime())) {
      if (currentEditingTask.value) {
        // 编辑模式：直接更新当前编辑任务
        currentEditingTask.value.reminder = reminderDateTime.toISOString()
      } else {
        // 新建模式：更新临时设置
        currentTaskSettings.reminder = reminderDateTime.toISOString()
      }
    } else {
      console.error('Invalid date/time values:', selectedReminderDate.value, selectedReminderTime.value)
      if (currentEditingTask.value) {
        currentEditingTask.value.reminder = null
      } else {
        currentTaskSettings.reminder = null
      }
    }
  } else {
    if (currentEditingTask.value) {
      currentEditingTask.value.reminder = null
    } else {
      currentTaskSettings.reminder = null
    }
  }
  reminderDialog.value = false
}

// 打开重复设置对话框
const openRepeatDialog = () => {
  selectedRepeat.value = currentTaskSettings.repeat
  repeatDialog.value = true
}

// 设置重复
const setRepeat = () => {
  let repeatValue
  if (selectedRepeat.value === 'custom') {
    repeatValue = `custom_${customRepeatDays.value}`
  } else {
    repeatValue = selectedRepeat.value
  }
  
  if (currentEditingTask.value) {
    // 编辑模式：直接更新当前编辑任务
    currentEditingTask.value.repeat = repeatValue ? {
      type: repeatValue.startsWith('custom_') ? 'custom' : repeatValue,
      customDays: repeatValue.startsWith('custom_') ? parseInt(repeatValue.split('_')[1]) : undefined
    } : undefined
  } else {
    // 新建模式：更新临时设置
    currentTaskSettings.repeat = repeatValue
  }
  repeatDialog.value = false
}

// 切换任务完成状态
const toggleTask = (task) => {
  storeToggleTask(task.id)
  console.log(`任务 "${task.title}" ${task.completed ? '已完成' : '未完成'}`)
}

// 删除任务
const deleteTask = (taskId) => {
  storeDeleteTask(taskId)
}

// 编辑边栏相关方法
const openEditDrawer = (task) => {
  currentEditingTask.value = { ...task }
  editDrawer.value = true
}

const closeEditDrawer = () => {
  editDrawer.value = false
  currentEditingTask.value = null
}

// 获取重复设置的显示文本
const getRepeatText = (repeat) => {
  if (!repeat || repeat.type === 'none') return '不重复'
  
  const typeMap = {
    daily: '每天',
    weekly: '每周',
    monthly: '每月',
    custom: '自定义'
  }
  
  if (repeat.type === 'custom' && repeat.customDays) {
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const selectedDays = repeat.customDays.map(day => dayNames[day]).join('、')
    return `自定义 (${selectedDays})`
  }
  
  return typeMap[repeat.type] || '不重复'
}

// 保存编辑的任务
const saveEditedTask = () => {
  if (currentEditingTask.value) {
    const { id, ...taskData } = currentEditingTask.value
    storeUpdateTask(id, taskData)
    closeEditDrawer()
  }
}

// 编辑模式下的对话框方法
const openDeadlineDialogForEdit = () => {
  if (currentEditingTask.value?.deadline) {
    selectedDeadline.value = new Date(currentEditingTask.value.deadline)
  } else {
    selectedDeadline.value = new Date()
  }
  deadlineDialog.value = true
}

const openReminderDialogForEdit = () => {
  if (currentEditingTask.value?.reminder) {
    const reminderDate = new Date(currentEditingTask.value.reminder)
    selectedReminderDate.value = reminderDate
    selectedReminderTime.value = reminderDate.toTimeString().slice(0, 5)
  } else {
    selectedReminderDate.value = new Date()
    selectedReminderTime.value = '09:00'
  }
  reminderDialog.value = true
}

const openRepeatDialogForEdit = () => {
  if (currentEditingTask.value?.repeat) {
    currentTaskSettings.repeat = currentEditingTask.value.repeat.type || 'none'
    if (currentEditingTask.value.repeat.customDays) {
      selectedCustomDays.value = [...currentEditingTask.value.repeat.customDays]
    }
  } else {
    currentTaskSettings.repeat = 'none'
    selectedCustomDays.value = []
  }
  repeatDialog.value = true
}
</script>

<style scoped>
.task-manager {
  padding: 16px;
}
</style>